#pragma once

#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include "Log.hpp"
#include <sstream>


class Util
{
public:

// 读取文件内容
// 网页文件：文本的
// 图片、音视频：二进制的
static bool ReadFile(const std::string &path, std::string *fileContent)
{
    // 获取文件大小，调整string空间，读取
    // man 2 stat
    struct stat st;
    int n = stat(path.c_str(), &st);
    if(n < 0)
        return false;
    int size = st.st_size;

    fileContent->resize(size);
    int fd = open(path.c_str(), O_RDONLY);
    if(fd < 0)
        return false;
    read(fd, (char*)fileContent->c_str(), size);

    close(fd);

    logMessage(Debug, "Read file %s success.", path.c_str());

    return true;
}

// 以sep为分隔符读取，并删除掉读取的部分包括sep
static std::string ReadOneLine(std::string&message, const std::string &sep)
{
    auto pos = message.find(sep);
    if(pos == std::string::npos)
        return "";
    std::string s = message.substr(0, pos);
    message.erase(0, pos + sep.size());
    return s;
}

// 解析http请求的第一行
// GET /favicon.ico HTTP/1.1
// GET /a/b/c/d HTTP/1.1
static bool ParseRequestLine(const std::string&line, std::string* method, std::string* url, std::string* httpVersion)
{
    std::stringstream ss(line);
    ss >> *method >> *url >> *httpVersion;
    return true;
}
};